package qzbook.cn.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import qzbook.cn.dao.RoleDao;
import qzbook.cn.pojo.Role;
import qzbook.cn.service.RoleService;

import java.util.List;

/**
 * @Description
 * @Author zc
 * @Date 2020/11/13 上午12:22
 */
@Service
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleDao roleDao;

    /**
     * 使用@Cacheable定义缓存策略
     * 当缓存中有值，则返回缓存数据，否则访问方法得到数据
     * 通过value引用缓存管理器，通过key定义键
     * @param id 角色编号
     * @return 角色对象
     * */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    @Cacheable(value = "redisCacheManager",key = "'redis_role_'+#id")
    public Role getRole(Long id) {
        return roleDao.getRole(id);
    }


    /**
     * 使用@CacheEvict删除缓存对应的key
     * @param id 角色编号
     * @return 返回删除记录数
     * */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    @CacheEvict(value = "redisCacheManager",key = "'redis_role_'+#id")
    public int deleteRle(Long id) {
        return roleDao.deleteRole(id);
    }


    /**
     * 使用@CachePut则表示无论如何都会执行方法，最后将方法的返回值在保存到缓存中
     * 使用在插入数据的地方，则标识保存到数据库后，会同期插入到Redis缓存中
     * @param role 绝对想
     * @return 角色随想 (会回填主键，在MyBatis中配置的)
     * */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    @CachePut(value = "redisCacheManager",key = "'redis_role_'+#role.id",unless = "#result.id <= 0")
    public Role insetRole(Role role) {
        int result = roleDao.insertRole(role);
        if (result <= 0){
            role = null;
        }
        return role;
    }

    /**
     * 使用@CachePut，表示更新数据库数据的同时，也会同步更新缓存
     * @param role 绝对想
     * @return 影响条数
     * */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    @CachePut(value = "redisCacheManager",key = "'redis_role_'+#result.id")
    public Role updateRole(Role role) {
        if (roleDao.updateRole(role) == 1){
            return role;
        }
        return null;
    }

    @Override
    public List<Role> findRoles(String roleName, String note) {
        return roleDao.findRoles(roleName,note);
    }

}
